//
// Created by hjie on 23-7-18.
//

#include "./../base/link.h"

void ProducerLinkList(LinkList & link_list, int number)
{
    srand(time(NULL) + rand() % 1000);

    link_list.head_node = new LinkNode();
    link_list.tail_node = link_list.head_node;

    link_list.head_node->data = rand() % 50;
    link_list.head_node->next_node = nullptr;
    link_list.head_node->prev_node = nullptr;

    for (int index = 0; index < number - 1; index++)
    {
        int data = link_list.tail_node->data + index + 2;
        LinkNode * node = new LinkNode();
        node->data = data;
        node->next_node = nullptr;
        node->prev_node = nullptr;

        link_list.tail_node->next_node = node;
        node->prev_node = link_list.tail_node;

        link_list.tail_node = node;
    }
    printf("producer data : ");
    LinkNode * ptr = link_list.head_node;
    while (ptr)
    {
        printf(" %d ", ptr->data);
        ptr = ptr->next_node;
    }
    printf("\n");
}

void MergeTwoLinkList()
{
    int length = 10;
    LinkList list_one{};
    LinkList list_two{};

    ProducerLinkList(list_one, length);
    ProducerLinkList(list_two, length);


    LinkNode * f1 = list_one.head_node;
    LinkNode * f2 = list_two.head_node;

    LinkList new_list;
    new_list.head_node = new_list.tail_node = nullptr;

    while (f1 || f2)
    {
        LinkNode * ptr = nullptr;
        if (f1 && f2)
        {
            if (f1->data > f2->data)
            {
                ptr = f2;
                f2 = f2->next_node;
            }
            else
            {
                ptr = f1;
                f1 = f1->next_node;
            }
        }
        else if (f1)
        {
            ptr = f1;
            f1  = f1->next_node;
        }
        else    // f2
        {
            ptr = f2;
            f2  = f2->next_node;
        }
        if (new_list.head_node == nullptr)
        {
            new_list.head_node = ptr;
            new_list.tail_node = ptr;
        }
        else
        {
            new_list.tail_node->next_node = ptr;
            new_list.tail_node = ptr;
        }
    }
    LinkNode * ptr = new_list.head_node;
    printf("result data : ");
    while(ptr)
    {
        printf("  %d  ", ptr->data);
        ptr = ptr->next_node;
    }
    printf("\n");
}

int main()
{
    MergeTwoLinkList();
    return 0;
}